package com.wnxy.sddfp.system.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sddfp.common.model.constant.MQConstant;
import com.wnxy.sddfp.common.model.dto.bank.BankCardRequestDto;
import com.wnxy.sddfp.system.entity.UserCard;
import com.wnxy.sddfp.system.entity.UserDetail;
import com.wnxy.sddfp.system.service.IUserCardService;
import com.wnxy.sddfp.system.service.IUserDetailService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class BindCardListener {

    private final IUserDetailService userDetailService;
    private final IUserCardService userCardService;

    public BindCardListener(IUserDetailService userDetailService, IUserCardService userCardService) {
        this.userDetailService = userDetailService;
        this.userCardService = userCardService;
    }

    /**
     * 监听指定队列中的消息
     *
     * @Payload 1、实现把消息的json格式转换为对象
     * 2、注意：需要配置消息转换器
     */
    @RabbitListener(queues = MQConstant.SDDFP_QUEUE_BIND)
    public void handlerMsg(@Payload BankCardRequestDto bankCardRequestDto) {

        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(() -> {
            // 1. 根据请求流水号，更新用户表u_user_detail中绑卡状态
            userDetailService.update(Wrappers.lambdaUpdate(UserDetail.class)
                    .set(UserDetail::getCardBindStatus, true)
                    .eq(UserDetail::getReqCode, bankCardRequestDto.getReqCode())
            );

        });

        // 2. 根据用户编码查询用户id
        UserDetail userDetail = userDetailService.getOne(
                Wrappers.lambdaQuery(UserDetail.class)
                        .select(UserDetail::getId)
                        .eq(UserDetail::getUserCode, bankCardRequestDto.getUserCode()));

        executorService.submit(() -> {
            // 3. 根据用户id修改u_user_card绑卡记录表中信息
            userCardService.update(Wrappers.lambdaUpdate(UserCard.class)
                    .set(UserCard::getBankNo, bankCardRequestDto.getBankNo())
                    .set(UserCard::getBankTitle, bankCardRequestDto.getBankTitle())
                    .set(UserCard::getStatus, true)
                    .eq(UserCard::getUserId, userDetail.getId())
            );
        });
        executorService.shutdown();// 关闭线程池
    }
}